# -*- coding: utf-8 -*-
# @Author : breeze
# @Date   : 2021/5/20
# @File   : EJ10_Ent3yearsCrimCaseCnt.py
# @E-mail : wangbaoshan@bbdservice.com

'''eof
name:申请企业近三年刑事案件数
code:EJ10_Ent3yearsCrimCaseCnt
tableName:
columnName:
groups:企业通用模块
dependencies:EG_CASE_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import json
from datetime import datetime


def format_data(tableName):
    try:
        eg = EG_CASE_DSJ.get("data").get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def get_date_list():
    try:
        now = datetime.now()
        aaa = [(now + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-36, 0]]
        return aaa
    except:
        return None


def isEmpty(*item):
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    for i in item:
        if i in null_type_list:
            return True
    return False


def get_result():
    try:
        alter_list = format_data("R227")
        if alter_list == [{}]:
            return u'缺失值'
        else:
            if len(alter_list) >= 1:
                factor = []
                date_list = get_date_list()
                for i in alter_list:
                    caseDate = i.get("CASEDATE")
                    caseNo = i.get("CASENO")
                    if isEmpty(caseDate,i.get("DOCUCLASS"),i.get("PTYPE")) \
                            or isEmpty(date_format(caseDate[0:10])) or caseNo in factor:
                        continue
                    # 1、Factor1 = 诉讼信息（R227）中公告类型（PTYPE）取值为16的案件。
                    # 2、Factor2 = Factor1中立案时间（CASEDATE）在指标计算日期三年内，
                    # 案件性质（DOCUCLASS）取值为“刑事案件---1”
                    # 并根据案号（CASENO)去重
                    try:
                        if date_list[0] < date_format(caseDate[0:10]) <= date_list[1] \
                                and i.get("DOCUCLASS") == "1" \
                                and i.get("PTYPE") == "16":
                            factor.append(caseNo)
                        else:
                            factor.append(None)
                    except:
                        continue
                factor2 = list(filter(lambda x: x is not None, factor))
                return len(factor2) if len(factor) > 0 else u'缺失值'
            else:
                return 0
    except:
        return u'缺失值'


if __name__ == "__main__":
    print("开始执行...")
    file_obj = open(r'E:\Z2需求文档\需求文档\重庆\司法\EG_CASE_DSJ.json', encoding='utf-8', mode='r')
    content = file_obj.read()
    EG_CASE_DSJ = json.loads(content, strict=False)
    aa = get_result()
    print("执行结束...{}".format(aa))

result = get_result()
